import $day, { FORMAT } from '@/utils/day'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export const useCounterStore = defineStore(
  'counter',
  () => {
    const count = ref(0)
    const name = ref('Counter')
    const lastUpdated = ref($day.format($day.now(), FORMAT.DATETIME))

    const doubleCount = computed(() => count.value * 2)
    const countPlusOne = computed(() => count.value + 1)

    const increment = () => {
      count.value++
      lastUpdated.value = $day.format($day.now(), FORMAT.DATETIME)
    }

    const decrement = () => {
      count.value--
      lastUpdated.value = $day.format($day.now(), FORMAT.DATETIME)
    }

    const reset = () => {
      count.value = 0
      lastUpdated.value = $day.format($day.now(), FORMAT.DATETIME)
    }

    return {
      // 状态
      count,
      name,
      lastUpdated,
      // getters
      doubleCount,
      countPlusOne,
      // actions
      increment,
      decrement,
      reset,
    }
  },
  {
    persist: {
      storage: {
        getItem: key => uni.getStorageSync(key),
        setItem: (key, value) => uni.setStorageSync(key, value),
      },
    },
  },
)
